
<script>
import { particularDates, deleteParticularDate } from '@/api/watchman'
import popconfirm from '../../components/Popconfirm/popconfirm.vue'

import CreateParticularDate from './particularDate/CreateParticularDate.vue'
import EditParticularDate from './particularDate/EditParticularDate.vue'

export default {
  components: {
    popconfirm,
    CreateParticularDate,
    EditParticularDate
  },
  data() {
    return {
      loadingStatuses: {
        loading: false
      },
      pagination: {
        size: 10,
        current: 1,
        total: 0
      },

      particularDates: [],

      isCreateDialogVisible: false,
      isEditDialogVisible: false,
      idToBeEdit: null,
      form: {}
    }
  },
  computed: {
    particularDatesFormatted() {
      return this.particularDates.map((item) => {
        const { id, date, created_at, updated_at, classes } = item
        return {
          id,
          date,
          createdAt: created_at,
          updatedAt: updated_at,
          name: classes?.name
        }
      })
    }
  },
  created() {
    this.initData()
  },
  methods: {
    handlePageChange(currentPage) {
      this.pagination.current = currentPage
      this.refreshTable()
    },
    handlePageSizeChange(size) {
      this.pagination.size = size
      this.refreshTable()
    },

    handleCreateSuccess() {
      this.isCreateDialogVisible = false
      this.refreshTable()
      this.$message.success('创建成功')
    },
    handleCreateFail() {
      this.isCreateDialogVisible = false
      this.$message.error('创建失败')
    },

    handleUpdateSuccess() {
      this.isEditDialogVisible = false
      this.refreshTable()
      this.$message.success('修改成功')
    },
    handleUpdateFail() {
      this.isEditDialogVisible = false
      this.$message.error('修改失败')
    },

    handleDeleteSuccess() {
      this.$message.success('删除成功')
      this.refreshTable()
    },
    handleDeleteFail() {
      this.$message.error('删除失败')
    },
    handleDelete(id) {
      return async() => {
        await this.sleep(300)
        await deleteParticularDate(id)
      }
    },

    showCreateDialog() {
      this.isCreateDialogVisible = true
    },
    showEditDialog(id) {
      this.idToBeEdit = id
      this.isEditDialogVisible = true
    },

    async refreshTable() {
      try {
        if (this.loadingStatuses.loading) return
        this.loadingStatuses.loading = true
        await this.sleep(400)
        await this.loadData()
        this.loadingStatuses.loading = false
      } catch (e) {
        this.loadingStatuses.loading = false
      }
    },
    sleep(t) {
      return new Promise((r) => setTimeout(r, t))
    },
    async getParticularDates() {
      const { current, size } = this.pagination
      const { date, class_name } = this.form
      const params = {
        page: current,
        paginate: size,
        sort: 'asc',
        date: JSON.stringify(date),
        class_name: class_name
      }
      const result = await particularDates(params)
      this.particularDates = result.data
      this.pagination.total = result.meta.total
    },
    async loadData() {
      const result = await Promise.allSettled([this.getParticularDates()])

      const failTasks = result.filter((task) => task.status === 'rejected')
      if (failTasks.length <= 0) return

      throw failTasks.at(0).reason
    },
    async initData() {
      try {
        this.loadingStatuses.loading = true
        await this.loadData()
        this.loadingStatuses.loading = false
      } catch (error) {
        this.loadingStatuses.loading = false
      }
    },
    onSubmit() {
      this.getParticularDates()
    }
  }
}
</script>
<template>
  <div class="app-container watchman-particular-date-container">
    <CreateParticularDate
      v-model="isCreateDialogVisible"
      @success="handleCreateSuccess"
      @fail="handleCreateFail"
    />
    <EditParticularDate
      :id="idToBeEdit"
      v-model="isEditDialogVisible"
      @success="handleUpdateSuccess"
      @fail="handleUpdateFail"
    />

    <el-card shadow="never" style="margin-bottom: 20px; border: none;">
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-form-item label="特殊日期" style="margin-bottom: 0">
          <el-date-picker
            v-model="form.date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="班次名称" style="margin-bottom: 0">
          <el-input v-model="form.class_name" placeholder="请输入班次名称" />
        </el-form-item>
        <el-form-item style="margin-bottom: 0">
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" style="border: none;">
      <el-row :gutter="40">
        <el-col :span="24">
          <div class="header-container">
            <el-button
              class="header-container__item"
              type="primary"
              icon="el-icon-plus"
              @click="showCreateDialog"
            >
              创建特殊日期
            </el-button>
            <el-button
              class="header-container__item"
              icon="el-icon-refresh-right"
              @click="refreshTable"
            >
              刷新
            </el-button>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-table
            v-loading="loadingStatuses.loading"
            :data="particularDatesFormatted"
            style="width: 100%"
            border
          >

            <el-table-column prop="date" label="日期" width="180" sortable />

            <el-table-column prop="name" label="班次名称" width="180" />

            <el-table-column prop="createdAt" label="创建时间" />

            <el-table-column prop="updatedAt" label="最后修改" />

            <el-table-column prop="actions" label="操作" fixed="right">
              <template slot-scope="scope">
                <div class="actions">
                  <el-button
                    circle
                    plain
                    type="primary"
                    icon="el-icon-edit"
                    @click="showEditDialog(scope.row.id)"
                  />

                  <popconfirm
                    :confirm-fn="handleDelete(scope.row.id)"
                    @success="handleDeleteSuccess"
                    @fail="handleDeleteFail"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-pagination
            style="padding-bottom: 0;"
            class="block"
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="pagination.current"
            :page-sizes="[10, 50, 100]"
            :page-size="pagination.size"
            :total="pagination.total"
            :disabled="loadingStatuses.loading"
            @size-change="handlePageSizeChange"
            @current-change="handlePageChange"
          />
        </el-col>
      </el-row>
    </el-card>

  </div>
</template>
<style lang="scss">
.watchman-particular-date-container {
  .el-pagination {
    padding: 16px 0;

    .btn-prev,
    .btn-next {
      margin: 0;
      margin-right: 6px;
    }
  }

  .header-container {
    padding-bottom: 20px;

    &__item {
      margin-right: 10px;
    }
  }

  .actions {
    .el-button {
      margin: 5px;
    }
  }
  .block{
    display: flex;
    justify-content: center;
  }
}
</style>
